package com.hopedove.workshop.ui.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hopedove.workshop.data.pojo.ObservableShiftQueryItem
import com.hopedove.workshop.databinding.WorkshopShiftChangeQueryListItemBinding

class ShiftChangeQueryAdapter : RecyclerView.Adapter<ShiftChangeQueryAdapter.VH>() {

    private val dataSet = mutableListOf<ObservableShiftQueryItem>()

    var allCheckedListener: ((Boolean) -> Unit)? = null

    @SuppressLint("NotifyDataSetChanged")
    fun setData(list: List<ObservableShiftQueryItem>) {
        dataSet.clear()
        dataSet.addAll(list)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val binding = WorkshopShiftChangeQueryListItemBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return VH(binding)
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        holder.binding.item = dataSet[position]

        holder.binding.tvCheck.setOnClickListener {
            dataSet[position].checked.set(holder.binding.tvCheck.isChecked)
            checkItemsStatus()
        }
    }

    override fun getItemCount(): Int = dataSet.size

    class VH(val binding: WorkshopShiftChangeQueryListItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    fun setAllCheckStatus(check: Boolean) {
        dataSet.filter { it.enableCheck }.forEach {
            it.checked.set(check)
        }
    }

    private fun checkItemsStatus() {
        val allChecked = dataSet.filter { it.enableCheck }.all { it.checked.get() }
        allCheckedListener?.invoke(allChecked)
    }
}